package com.eve.eplus.service;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.eve.eplus.R;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.sns.weibo.WeiboAPIGather;

public class SendMsgService extends Service
{

    private static final int NOTIFY_ID = 0;
    private static final int OK = 1;
    private static final int ERROR = 0;
    private static final int CANCEL = -1;
    private boolean cancelled;
    private int progress;

    private Context mContext = this;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private Notification.Builder mBuilder;

    private SendBinder binder = new SendBinder();

    private ArrayList<HashMap<String, String>> mAccountInfo;
    private String mContent;
    private String mUri;
    private int finishCount; // 完成数

    @Override
    public IBinder onBind(Intent intent)
    {
        // TODO Auto-generated method stub
        return binder;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        cancelled = true; // 取消
    }

    public class SendBinder extends Binder
    {

        /**
         * 开始下载
         */
        public void start(ArrayList<HashMap<String, String>> accountInfo,
                String Content, String uri)
        {
            mAccountInfo = accountInfo;
            mContent = Content;
            mUri = uri;
            // 总数清零
            finishCount = 0;
            // 将进度归零
            progress = 0;
            // 创建通知
            setNotification();
            // 开始发送
            startSending();

        }

        /**
         * 获取进度
         * 
         * @return
         */
        public int getProgress()
        {
            return progress;
        }

        /**
         * 取消
         */
        public void cancel()
        {
            cancelled = true;
        }

        /**
         * 是否已被取消
         * 
         * @return
         */
        public boolean isCancelled()
        {
            return cancelled;
        }

    }

    /**
     * 发送信息
     */
    private void startSending()
    {
        cancelled = false;
        send();
    }

    private void send()
    {
        Message msg;
        for (int i = 0; i < mAccountInfo.size(); i++)
        {
            if (!cancelled)
                /**
                 * 发送微博
                 */
                if (mUri != null)
                    new WeiboAPIGather(mAccountInfo.get(i), new Handler() {
                        @Override
                        public void handleMessage(Message msg)
                        {
                            // TODO Auto-generated method stub
                            super.handleMessage(msg);
                            switch (msg.what)
                            {
                                case Constants.MSG_WEIBO_UPLOAD_OK:
                                    finishCount++;
                                    msg = new Message();
                                    msg.what = OK;
                                    msg.arg1 = finishCount;
                                    handler.sendMessage(msg);
                                    LogTools.info("收到消息:MSG_WEIBO_UPLOAD_OK****"+finishCount);
                                    break;

                                default:
                                    break;
                            }
                        }
                    }).setUpload(mContent, mUri, "0", "0");
                else
                    new WeiboAPIGather(mAccountInfo.get(i), new Handler() {
                        @Override
                        public void handleMessage(Message msg)
                        {
                            // TODO Auto-generated method stub
                            super.handleMessage(msg);
                            switch (msg.what)
                            {
                                case Constants.MSG_WEIBO_UPDATE_OK:
                                    finishCount++;
                                    msg = new Message();
                                    msg.what = OK;
                                    msg.arg1 = finishCount;
                                    handler.sendMessage(msg);
                                    LogTools.info("收到消息:MSG_WEIBO_UPDATE_OK****"+finishCount);
                                    break;

                                default:
                                    break;
                            }
                        }
                    }).setUpdate(mContent, "0", "0");
            else
            {
                msg = handler.obtainMessage();
                msg.what = CANCEL;
                handler.sendMessage(msg);
            }
        }
    }

    /**
     * 创建通知
     */
    private void setNotification()
    {
        mBuilder = new Notification.Builder(mContext);
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setTicker("正在为您发送微薄...");
        mBuilder.setWhen(System.currentTimeMillis());
        mBuilder.setAutoCancel(true);
        mBuilder.setContentTitle("正在为您发送微薄...");
        mNotification = mBuilder.getNotification();
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case OK:
                    int rate = msg.arg1;
                    LogTools.info("已发送微薄数"+rate);
                    if (rate < mAccountInfo.size())
                    {
                        // 更新进度
/*                        RemoteViews contentView = mNotification.contentView;
                        contentView.setTextViewText(R.id.tv_persent, rate + "/"
                                + mAccountInfo.size());
                        contentView.setProgressBar(R.id.progress,
                                mAccountInfo.size(), rate, false);*/
                    	mBuilder = new Notification.Builder(mContext);
                        mBuilder.setContentTitle("正在为您发送微薄...");
                        mBuilder.setSmallIcon(R.drawable.ic_launcher);
                        mBuilder.setTicker("已完成："+rate+"/"+mAccountInfo.size());
                        mBuilder.setContentText("已完成："+rate+"/"+mAccountInfo.size());
                        mBuilder.setWhen(System.currentTimeMillis());
                        mBuilder.setAutoCancel(true);
                        mNotification = mBuilder.getNotification();
                    }
                    else
                    {
                        // 下载完毕后变换通知形式
                        mBuilder = new Notification.Builder(mContext);
                        mBuilder.setContentTitle("发送完毕");
                        mBuilder.setSmallIcon(R.drawable.ic_launcher);
                        mBuilder.setTicker("发送完毕");
                        mBuilder.setWhen(System.currentTimeMillis());
                        mBuilder.setAutoCancel(true);
                        mNotification = mBuilder.getNotification();
                        stopSelf();// 停掉服务自身
                    }

                    // 通知更新
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    break;
                case CANCEL:
                    // 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    break;
            }
        };
    };

}
